package com.liu.mybatisplusdemo.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liu.mybatisplusdemo.entity.ExcelGoods;
import com.liu.mybatisplusdemo.entity.Goods;
import com.liu.mybatisplusdemo.service.GoodsService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping(value = "/goods")
public class GoodsController {

    @Resource
    GoodsService goodsService;

    @GetMapping(value = "/export",produces = "application/json; charset=utf-8")
    public String exportGoods(HttpServletResponse response) throws IOException {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("state","1");
        List<Goods> goods = goodsService.list(queryWrapper);

        List<ExcelGoods> excelGoodsList = new ArrayList<>();
        for (int i = 0; i < goods.size(); i++) {
            Goods goods1 = goods.get(i);
            ExcelGoods excelGoods = new ExcelGoods();
            excelGoods.setCount(goods1.getCount());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String time = sdf.format(new Date(goods1.getCreatetime()));
            excelGoods.setCreatetime(time);
            excelGoods.setName(goods1.getName());
            excelGoods.setState(goods1.getState()==0?"无效":"有效");
            excelGoodsList.add(excelGoods);
        }

        // 设置文本内省
        response.setContentType("application/vnd.ms-excel");
        // 设置字符编码
        response.setCharacterEncoding("utf-8");
        // 设置响应头
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String time = sdf.format(new Date(System.currentTimeMillis()));

        response.setHeader("Content-disposition", "attachment;filename=" + time + ".xlsx");
        EasyExcel.write(response.getOutputStream(), ExcelGoods.class).sheet("商品列表").doWrite(excelGoodsList);

        return "success";
    }
}
